package com.example.paging.ui

import androidx.lifecycle.*
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.paging.entity.HomeVO
import com.example.paging.repository.ArticleRepository
import kotlinx.coroutines.flow.Flow

class HomeVoViewModel : ViewModel() {

    private val homeVO: MutableLiveData<HomeVO> by lazy {
        MutableLiveData<HomeVO>().also {
            loadHomeVO()
        }
    }


    private val articleLiveData : MutableLiveData<PagingData<HomeVO.Data.Datas>> by lazy {
       MutableLiveData<PagingData<HomeVO.Data.Datas>>().also {
           ArticleRepository.getArticleData().asLiveData()
       }
    }


    fun getArticle() = articleLiveData

    val pager by lazy {
        Pager(
            config = PagingConfig(pageSize = 20, prefetchDistance = 1),
            pagingSourceFactory = { HomePageSource() }).flow.cachedIn(viewModelScope)
    }

    fun getHomeVO(): LiveData<HomeVO> {
        return homeVO
    }

    private fun loadHomeVO(): LiveData<Result<HomeVO>> {
        return ArticleRepository.getHomeVo(0)
    }
}